const express = require('express');
const fs = require('fs');
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = 3000;
const MOCK_DIR = path.join(__dirname, 'mock');

// 中间件
app.use(cors());
app.use(express.json());

// 统一响应格式
const createResponse = (code, message, data = null) => {
  return {
    code,
    message,
    data
  };
};

// 辅助函数：读取指定 JSON 文件
const readJsonFile = (filename) => {
  try {
    const rawData = fs.readFileSync(path.join(MOCK_DIR, filename));
    return JSON.parse(rawData);
  } catch (err) {
    console.error(`Error reading ${filename}:`, err);
    return []; // 返回空数组
  }
};



// 菜品接口
app.get('/api/dishes', (req, res) => {
  try {
    const dishes = readJsonFile('cookbook-list.json');
    res.json(createResponse(200, '获取菜品', dishes));
  } catch (error) {
    res.status(500).json(createResponse(500, '获取菜品列表失败'));
  }
});

// 热门分类接口
app.get('/api/hotCat', (req, res) => {
  try {
    const categories = readJsonFile('cookbook-hotcat.json');
    res.json(createResponse(200, '获取热门分类成功', categories));
  } catch (error) {
    res.status(500).json(createResponse(500, '获取热门分类失败'));
  }
});



// 启动服务器
app.listen(PORT, () => {
  console.log(`点餐系统API已启动：http://localhost:${PORT}`);
});